import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    View,
    Button,
    TextInput,
    FlatList,
    RefreshControl,
    ActivityIndicator,
    Alert,
    AsyncStorage,
    TouchableOpacity,
    TouchableHighlight,
    Image
} from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast'
import NavigationBar from '../common/NavigationBar';
import DataRepository, {FLAG_STORAGE} from '../expand/dao/DataRepository';
const URL = 'https://github.com/trending/';

import ScrollableTabView ,{ScrollableTabBar} from 'react-native-scrollable-tab-view';
import LanguageDao, {FLAG_LANGUAGE}  from "../expand/dao/LanguageDao";
import TrendingCell from '../common/TrendingCell';

import TimeSpan from '../common/model/TimeSpan';
var timeSpanTextArray = [new TimeSpan('今天', 'since=daily'), new TimeSpan('本周', 'since=weekly'), new TimeSpan('本月', 'since=monthly')];

//右边更多菜单组件
import ViewUtils from '../common/util/ViewUtils';
import MoreMenu, {MORE_MENU} from '../common/MoreMenu';
import TrendingDialog from "../common/TrendingDialog";
// 下拉选择日期


export default class TrendingPage extends Component {
    constructor(props){
        super(props);
        this.dataRepository = new DataRepository(FLAG_STORAGE.flag_trending);
        this.languageDao = new LanguageDao(FLAG_LANGUAGE.flag_language)
        this.state = {
            result:'',
            languages: [],
            timeSpan:timeSpanTextArray[0]
        }
    }
    componentWillMount(){
        this.onLoad();
    }
    onLoad(){
        this.languageDao.fetchData()
            .then(result=>{
                this.setState({
                    languages: result
                })
            })
            .catch(error=>{
                console.log(error)
            })
    }
    renderMoreView(){
        return <MoreMenu
            ref="moreMenu"
            menus={[MORE_MENU.Custom_Language, MORE_MENU.Custom_Theme, MORE_MENU.Sort_Language]}
            {...this.props}
        />
    }
    closePopover() {
        this.dialog.dismiss();
    }
    onSelectTimeSpan(timeSpan){
        this.closePopover();
        this.setState({
            timeSpan: timeSpan
        })
    }
    renderDropDownSelect(){
        return <TrendingDialog
            ref={dialog => this.dialog = dialog}
            onSelect={(tab)=>this.onSelectTimeSpan(tab)}
        />
    }
    render(){
        let content = this.state.languages.length > 0 ?
            <ScrollableTabView
                tabBarInactiveTextColor="mintcream"
                tabBarActiveTextColor="white"
                tabBarUnderlineStyle={{backgroundColor: '#e7e7e7', height: 2}}
                tabBarBackgroundColor="#2196f3"
                locked={true}
                renderTabBar={()=><ScrollableTabBar/>}
                initialPage={0}
            >
                {this.state.languages.map((resultItem, i, arr)=>{
                    return resultItem.checked ? <TrendingTab key={i} tabLabel={resultItem.name} timeSpan={this.state.timeSpan} {...this.props}></TrendingTab> : null;
                })}
            </ScrollableTabView> : null;
        return (
            <View style={styles.container}>
                <NavigationBar
                    statusBar={{
                        backgroundColor:'#2196f3'
                    }}
                    title={'趋势'}
                    style = {{
                        backgroundColor: '#2196f3'
                    }}
                    dropDownSelect={ViewUtils.getDropDownSelect(()=>{
                        this.dialog.show();
                    })}
                    rightButton={ViewUtils.getMoreButton(()=>{
                        this.refs.moreMenu.open();
                    })}
                />
                {content}
                {this.renderMoreView()}
                {this.renderDropDownSelect()}
            </View>
        )
    }
}

class TrendingTab extends Component {
    constructor(props){
        super(props);
        this.dataRepository = new DataRepository(FLAG_STORAGE.flag_trending);
        this.state = {
            result: '',
            dataSource: [],
            isLoading:false
        }
    }
    componentDidMount(){
        this.loadData(this.props.timeSpan, true);
    }
    componentWillReceiveProps(nextProps){
       if(nextProps.timeSpan !== this.props.timeSpan) {
           this.loadData(nextProps.timeSpan)
       }
    }
    loadData(timeSpan, isRefresh){
        this.setState({
            isLoading: true
        })
        let url = URL+ this.props.tabLabel + '?'+ timeSpan.searchText;

        this.dataRepository.fetchRepository(url)
            .then(result=>{
                console.log('result', result)
                let items = result && result.items ? result.items : result ? result : [];
                this.setState({
                    dataSource: items,
                    isLoading: false
                })
                if (result && result.update_data && !this.dataRepository.checkData(result.update_data)) {
                    this.refs.toast.show('数据过时', 500);
                    return this.dataRepository.fetchNetRepository(url);
                }else {
                    this.refs.toast.show('显示缓存数据');
                }
            })
            .then(items=>{
                if(!items || items.length ===0) return;
                this.setState({
                    dataSource: items
                    /*                        [
                                            {
                                                id: 6498492,
                                                node_id: "MDEwOlJlcG9zaXRvcnk2NDk4NDky",
                                                name: "javascript",
                                                full_name: "airbnb/javascript",
                                                owner: {
                                                    login: "airbnb",
                                                    id: 698437,
                                                    node_id: "MDEyOk9yZ2FuaXphdGlvbjY5ODQzNw==",
                                                    avatar_url: "https://avatars3.githubusercontent.com/u/698437?v=4",
                                                    gravatar_id: "",
                                                    url: "https://api.github.com/users/airbnb",
                                                    html_url: "https://github.com/airbnb",
                                                    followers_url: "https://api.github.com/users/airbnb/followers",
                                                    following_url: "https://api.github.com/users/airbnb/following{/other_user}",
                                                    gists_url: "https://api.github.com/users/airbnb/gists{/gist_id}",
                                                    starred_url: "https://api.github.com/users/airbnb/starred{/owner}{/repo}",
                                                    subscriptions_url: "https://api.github.com/users/airbnb/subscriptions",
                                                    organizations_url: "https://api.github.com/users/airbnb/orgs",
                                                    repos_url: "https://api.github.com/users/airbnb/repos",
                                                    events_url: "https://api.github.com/users/airbnb/events{/privacy}",
                                                    received_events_url: "https://api.github.com/users/airbnb/received_events",
                                                    type: "Organization",
                                                    site_admin: false
                                                },
                                                private: false,
                                                html_url: "https://github.com/airbnb/javascript",
                                                description: "JavaScript Style Guide",
                                                fork: false,
                                                url: "https://api.github.com/repos/airbnb/javascript",
                                                forks_url: "https://api.github.com/repos/airbnb/javascript/forks",
                                                keys_url: "https://api.github.com/repos/airbnb/javascript/keys{/key_id}",
                                                collaborators_url: "https://api.github.com/repos/airbnb/javascript/collaborators{/collaborator}",
                                                teams_url: "https://api.github.com/repos/airbnb/javascript/teams",
                                                hooks_url: "https://api.github.com/repos/airbnb/javascript/hooks",
                                                issue_events_url: "https://api.github.com/repos/airbnb/javascript/issues/events{/number}",
                                                events_url: "https://api.github.com/repos/airbnb/javascript/events",
                                                assignees_url: "https://api.github.com/repos/airbnb/javascript/assignees{/user}",
                                                branches_url: "https://api.github.com/repos/airbnb/javascript/branches{/branch}",
                                                tags_url: "https://api.github.com/repos/airbnb/javascript/tags",
                                                blobs_url: "https://api.github.com/repos/airbnb/javascript/git/blobs{/sha}",
                                                git_tags_url: "https://api.github.com/repos/airbnb/javascript/git/tags{/sha}",
                                                git_refs_url: "https://api.github.com/repos/airbnb/javascript/git/refs{/sha}",
                                                trees_url: "https://api.github.com/repos/airbnb/javascript/git/trees{/sha}",
                                                statuses_url: "https://api.github.com/repos/airbnb/javascript/statuses/{sha}",
                                                languages_url: "https://api.github.com/repos/airbnb/javascript/languages",
                                                stargazers_url: "https://api.github.com/repos/airbnb/javascript/stargazers",
                                                contributors_url: "https://api.github.com/repos/airbnb/javascript/contributors",
                                                subscribers_url: "https://api.github.com/repos/airbnb/javascript/subscribers",
                                                subscription_url: "https://api.github.com/repos/airbnb/javascript/subscription",
                                                commits_url: "https://api.github.com/repos/airbnb/javascript/commits{/sha}",
                                                git_commits_url: "https://api.github.com/repos/airbnb/javascript/git/commits{/sha}",
                                                comments_url: "https://api.github.com/repos/airbnb/javascript/comments{/number}",
                                                issue_comment_url: "https://api.github.com/repos/airbnb/javascript/issues/comments{/number}",
                                                contents_url: "https://api.github.com/repos/airbnb/javascript/contents/{+path}",
                                                compare_url: "https://api.github.com/repos/airbnb/javascript/compare/{base}...{head}",
                                                merges_url: "https://api.github.com/repos/airbnb/javascript/merges",
                                                archive_url: "https://api.github.com/repos/airbnb/javascript/{archive_format}{/ref}",
                                                downloads_url: "https://api.github.com/repos/airbnb/javascript/downloads",
                                                issues_url: "https://api.github.com/repos/airbnb/javascript/issues{/number}",
                                                pulls_url: "https://api.github.com/repos/airbnb/javascript/pulls{/number}",
                                                milestones_url: "https://api.github.com/repos/airbnb/javascript/milestones{/number}",
                                                notifications_url: "https://api.github.com/repos/airbnb/javascript/notifications{?since,all,participating}",
                                                labels_url: "https://api.github.com/repos/airbnb/javascript/labels{/name}",
                                                releases_url: "https://api.github.com/repos/airbnb/javascript/releases{/id}",
                                                deployments_url: "https://api.github.com/repos/airbnb/javascript/deployments",
                                                created_at: "2012-11-01T23:13:50Z",
                                                updated_at: "2018-06-02T00:53:35Z",
                                                pushed_at: "2018-06-01T00:13:44Z",
                                                git_url: "git://github.com/airbnb/javascript.git",
                                                ssh_url: "git@github.com:airbnb/javascript.git",
                                                clone_url: "https://github.com/airbnb/javascript.git",
                                                svn_url: "https://github.com/airbnb/javascript",
                                                homepage: null,
                                                size: 2800,
                                                stargazers_count: 71563,
                                                watchers_count: 71563,
                                                language: "JavaScript",
                                                has_issues: true,
                                                has_projects: false,
                                                has_downloads: true,
                                                has_wiki: true,
                                                has_pages: true,
                                                forks_count: 13677,
                                                mirror_url: null,
                                                archived: false,
                                                open_issues_count: 130,
                                                license: {
                                                    key: "mit",
                                                    name: "MIT License",
                                                    spdx_id: "MIT",
                                                    url: "https://api.github.com/licenses/mit",
                                                    node_id: "MDc6TGljZW5zZTEz"
                                                },
                                                forks: 13677,
                                                open_issues: 130,
                                                watchers: 71563,
                                                default_branch: "master",
                                                score: 89.117004
                                            }
                                            ]*/
                })
                this.refs.toast.show('显示网络数据');
            })
            .catch(error=>{
                this.setState({
                    result: JSON.stringify(error)
                })
            })
    }
    genIndicator(){
        return <View style={styles.indicatorContainer}>
            <ActivityIndicator
                style={styles.indicator}
                color={'red'}
                size = {'large'}
                animating={true}
            />
            {/*<Text>正在加载更多</Text>*/}
        </View>
    }
    _renderItem(data) {
        return <TrendingCell
            onSelect={this.onSelect.bind(this)}
            data={data}
        />
    }
    onSelect(data,result){
        this.props.navigation.navigate('RepositoryDetail',{dataFather: data})
    }
    render(){
        return (
            <View style={{flex: 1}}>
                <FlatList
                    data={this.state.dataSource}
                    renderItem={(data)=>this._renderItem(data)}
                    keyExtractor={(data, index)=>data.index}
                    //个性定制
                    refreshControl={
                        <RefreshControl
                            title={"Loading"}
                            colors={['#2196f3']}
                            refreshing={this.state.isLoading}
                            onRefresh={()=>{
                                this.loadData(this.props.timeSpan,true);
                            }}
                        />
                    }
                    /* ListFooterComponent = {()=>this.genIndicator()}*/
                    //优化组件
                    getItemLayout={(data, index) => (
                        // 120 是被渲染 item 的高度 ITEM_HEIGHT。
                        {length: 120, offset: 120 * index, index}
                    )}
                    /*  onEndReached = {()=>{
                          this.loadData()
                      }}*/
                />
                <Toast
                    ref="toast"
                    position='top'
                    positionValue={200}
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex:1
    },
    text:{
        fontSize: 18
    }
})